package com.sanbi.shield.server.shield;

import com.sanbi.shield.server.facade.constants.ShieldBizConstants;
import org.springframework.core.annotation.Order;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Shield拦截器
 *
 * @author XiaoQingqing
 * @since 2024/07/27
 */
@Order(Integer.MIN_VALUE)
public class ShieldInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        String userId = request.getHeader(ShieldBizConstants.SHIELD_USER_ID_HEADER_NAME);
        ShieldContext.setUserId(StringUtils.hasText(userId) ? Long.parseLong(userId) : null);
        return true;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest request,@NonNull  HttpServletResponse response, @NonNull Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        ShieldContext.clear();
    }
}
